<template>
  <el-card shadow="never">
    <template #header>
      <div class="card-header">
        <span>图片上传</span>
      </div>
    </template>
    <div class="component-upload-image">
      <el-upload
        multiple
        :action="uploadFileUrl"
        list-type="picture-card"
        :on-success="handleUploadSuccess"
        :before-upload="handleBeforeUpload"
        :limit="limit"
        :on-error="handleUploadError"
        :on-exceed="handleExceed"
        ref="imageUpload"
        :disabled="disabled"
        :before-remove="handleDelete"
        :show-file-list="true"
        :headers="headers"
        :file-list="fileList"
        :on-preview="handlePictureCardPreview"
        :class="{ hide: fileList.length >= limit }"
      >
      <i class="el-icon-plus"></i>

      </el-upload>
      <!-- 上传提示 -->
      <div class="el-upload__tip" v-if="showTip">
        请上传
        <template v-if="fileSize">
          大小不超过
          <b style="color: #f56c6c">{{ fileSize }}MB</b>
        </template>
        <template v-if="fileType">
          格式为
          <b style="color: #f56c6c">{{ fileType.join("/") }}</b>
        </template>
        的文件
      </div>

      <el-dialog
        v-model="dialogVisible"
        title="预览"
        width="800px"
        append-to-body
      >
        <img
          :src="dialogImageUrl"
          style="display: block; max-width: 100%; margin: 0 auto"
        />
      </el-dialog>
    </div>
  </el-card>
</template>

<script>
import { getToken } from "@/utils/auth";

export default {
  props: {
    // 图片数量限制
    limit: {
      type: Number,
      default: 5,
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 5,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["png", "jpg", "jpeg"],
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      default: false,
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: false,
    },
    // 是否显示提示
    businessId: {
      type: String,
      default: "",
    },
    // 是否显示提示
    businessType: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      uploadFileUrl:
        process.env.VUE_APP_BASE_API + "/steel-arch/client/file/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileList: [],
      uploadList: [],
      dialogImageUrl: "",
      dialogVisible: "",
      number: 0,
    };
  },
  computed: {
    showTip: function () {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
  },
  methods: {
    setUrl(url) {
      this.fileList = [];
      if (url) {
        let urls = url.split(",");
        for (let u of urls) {
          this.fileList.push({
            name: u,
            url: u,
            id: u,
          });
          console.info(this.fileList)
        }
      }
    },
    getUrl() {
      if (this.fileList && this.fileList.length > 0) {
        let urls = [];
        this.fileList.forEach((element) => {
          urls.push(element.url);
        });
        return urls.join(",");
      }
      return "";
    },
    // 上传前loading加载
    handleBeforeUpload(file) {
      let isImg = false;
      if (this.fileType.length) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        isImg = this.fileType.some((type) => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
      } else {
        isImg = file.type.indexOf("image") > -1;
      }
      if (!isImg) {
        this.$message.error(
          `文件格式不正确, 请上传${this.fileType.join("/")}图片格式文件!`
        );
        return false;
      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$message.error(`上传头像图片大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      // this.$message.loading("正在上传图片，请稍候...");
      this.number++;
    },
    // 文件个数超出
    handleExceed() {
      this.$message.error(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传失败
    handleUploadError(err) {
      this.$message.error("上传失败, 请重试");
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      this.$message.success("上传成功");
      console.info(this.fileList);
      debugger;
      if (res.success) {
        this.uploadList.push({
          name: res.data,
          url: res.data,
          id: res.data,
        });
        this.uploadedSuccessfully();
      } else {
        this.number--;
        this.$message.error(res.msg);
        this.$refs.imageUpload.handleRemove(file);
        this.uploadedSuccessfully();
      }
    },
    // 删除文件
    handleDelete(file) {
      const findex = this.fileList.map((f) => f.name).indexOf(file.name);
      if (findex > -1 && this.uploadList.length === this.number) {
        this.fileList.splice(findex, 1);
        return false;
      }
    },
    uploadedSuccessfully() {
      if (this.number > 0 && this.uploadList.length === this.number) {
        this.fileList = this.fileList
          .filter((f) => f.url !== undefined)
          .concat(this.uploadList);
        this.uploadList = [];
        console.info(this.fileList);
        this.number = 0;
      }
    },
    // 预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
  },
};
</script>
<style scoped lang="scss">
// .el-upload--picture-card 控制加号部分
:deep(.hide .el-upload--picture-card) {
  display: none;
}
.card-header {
  height: 5px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.box-card {
  width: 480px;
}
</style>
